import { getMatchCommonEvents, getMatchCommonParams, formatEvents, addCommonParamsBySourceType } from './multi-params-util.js';
import { getVmPageStatus } from '@/utils/util';
import { mapState } from 'vuex';

export default {
  computed: {
    ...mapState({
      commonParamsUpdatedEvtKeys: state => state.VisualComponentsModule.commonParamsUpdatedEvtKeys,
      allComponentsReady: state => state.VisualComponentsModule.allComponentsReady,
    }),
  },
  watch: {
    commonParamsUpdatedEvtKeys(evtKeys) {
      if (this.allComponentsReady) {
        const compEvtKeys = this.config.events.filter(n => n.type === 'in' && n.key).map(n => n.key);
        const hasEvt = evtKeys.some(key => compEvtKeys.includes(key));
        if (hasEvt) {
          const pageStatus = getVmPageStatus(this);
          this.updateParams(pageStatus);
          this.debounceGetData();
        }
      }
    },
  },

  methods: {

    // 补充公共参数
    addCommonParams(_dataSourceType = '') {
      const { events } = this.config;
      if (!events) {
        return;
      }
      const matchEvents = getMatchCommonEvents(events);
      const matchParams = getMatchCommonParams(matchEvents);

      let { data } = this.config.config;

      // 适配左xx右xx组件data格式
      if (this.curComp) {
        data = data[this.curComp];
      }
      const dataSourceType = _dataSourceType || data.dataSourceType;
      if (['xMiner', 'xMinerPublicDatabase', 'fabric', 'Dac'].includes(dataSourceType)) {
        this.params.params = addCommonParamsBySourceType(dataSourceType, this.params.params, matchParams);
      } else if (dataSourceType === 'xTag') {
        addCommonParamsBySourceType(dataSourceType, this.params, matchParams);
      } else {}

      // 记录事件
      const fEvents = formatEvents(matchEvents);
      fEvents.forEach(n => {
        this.addReceivedEvents(n, 'common');
      });
    },
  },
};
